public class Practice4 {
    /*https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
     翻转链表, 我是采用边走边看的方式判断是否翻转
     也可以采用读取链表的长度, 然后除k, 判断要翻转几次, 然后进行翻转最后连接没有翻转的链表
    */
    public boolean judgeRe(ListNode head,int k){
        //判断是否可以进行翻转
        ListNode cur = head;
        boolean flag = true;
        while(--k > 0){
            cur = cur.next;
            if(cur== null){
                flag = false;
                break;
            }
        }
        return flag;
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode phead = new ListNode(-1);
        ListNode prev = phead;
        ListNode cur = head;
        while(true){
            if(cur != null && judgeRe(cur,k)){
                ListNode pphead = new ListNode(-1);
                ListNode pprev = pphead;

                int n = k;
                //进行头插法翻转
                while(n-- > 0){
                    ListNode next = cur.next;
                    cur.next = pprev.next;
                    pprev.next = cur;
                    cur = next;
                }
                prev.next = pphead.next;
                //翻转完成后重新指向最后一个元素
                while(prev.next != null){
                    prev = prev.next;
                }
            }else{
                //不可以反转就指向最后没有翻转的部分
                prev.next = cur;
                break;
            }
        }
        return phead.next;
    }
}
class ListNode {
     int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
